<template>
    <div class="login-wrap">
        <div class="ms-login">
            <div class="ms-title">后台管理系统</div>
            <el-form :model="param" :rules="rules" ref="login" label-width="0px" class="ms-content">

                <el-form-item prop="username">
                    <el-input v-model="param.username" :placeholder="placeholder1">
                        <el-button slot="prepend" :icon="icon1"></el-button>
                        <template #append>
                            <el-select v-model="param.role" style="width: 130px;">
                                <el-option label="管理员" value="admin"></el-option>
                                <el-option label="商家" value="seller"></el-option>
                            </el-select>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input
                            type="password"
                            :placeholder="placeholder2"
                            v-model="param.password"
                    >
                        <el-button slot="prepend" icon="el-icon-lx-lock"></el-button>

                        <el-button v-if='loginType==="phone"' @click="getCode" slot="suffix" type="text"
                                   :class="{'disabled-style':getCodeBtnDisable}" :disabled="getCodeBtnDisable">
                            {{codeBtnWord}}
                        </el-button>
                        <!--                        <el-button v-if='loginType==="phone"' @click='getCode' style="padding-right:10px" slot="suffix" type="text" >获取验证码</el-button>-->
                    </el-input>

                </el-form-item>
                <div class="login-btn">
                    <el-button type="primary" @click="submitForm()">登录</el-button>
                </div>
                <div class='phone-login'>
                    <el-button @click='changeLoginType' type="text">{{otherLoginTitle}}</el-button>
                </div>

            </el-form>
        </div>
    </div>
</template>

<script>
    import axios from "axios";

    export default {

        data: function () {
            return {
                codeBtnWord: '获取验证码', // 获取验证码按钮文字
                waitTime: 61, // 获取验证码按钮失效时间
                icon1: 'el-icon-lx-people',
                placeholder1: 'username',
                placeholder2: 'password',
                otherLoginTitle: '手机号登录',
                loginType: 'pwd', //登录类型，密码登录pwd，手机号登录phone
                phoneLoginForm: {
                    phone: '',
                    code: '',
                    role: ''
                },
                param: {
                    username: '',
                    role: 'admin', //默认管理员登录
                    password: '',
                },
                rules: {
                    username: [{required: true, message: '请输入用户名或手机号', trigger: 'blur'}],
                    password: [{required: true, message: '请输入密码或验证码', trigger: 'blur'}],
                },
            };
        },
        computed: {
            // 用于校验手机号码格式是否正确
            phoneNumberStyle() {
                let reg = /^1[3456789]\d{9}$/
                if (!reg.test(this.param.username)) {
                    return false
                }
                return true
            },
            // 控制获取验证码按钮是否可点击
            getCodeBtnDisable: {
                get() {
                    if (this.waitTime == 61) {
                        if (this.param.username) {
                            return false
                        }
                        return true
                    }
                    return true
                },
                // 注意：因为计算属性本身没有set方法，不支持在方法中进行修改，而下面我要进行这个操作，所以需要手动添加
                set() {
                }
            }
        },
        methods: {
            //获取验证码
            getCode() {
                if (this.param.username === null || this.param.username === '') {
                    this.$message.error('请先输入手机号')
                    return false;
                }
                console.log('已输入')
                let myreg = /^[1][3,4,5,6.7,8,9][0-9]{9}$/;
                if (!myreg.test(this.param.username)) {
                    this.$message.error('手机号格式不正确')
                    return false;
                }
                console.log('格式正确')
                const _this = this;
                this.$http.get('dev-api/user/getCode/login/' + this.param.username)
                    .then(function (resp) {
                        if (resp.data.code === 0) {
                            _this.$message.success("验证码发送成功，请注意查收")
                        } else {
                            _this.$message.error(resp.data.msg)
                        }
                    })

                // 因为下面用到了定时器，需要保存this指向
                let that = this
                that.waitTime--
                that.getCodeBtnDisable = true
                this.codeBtnWord = `${this.waitTime}s 后重新获取`
                let timer = setInterval(function () {
                    if (that.waitTime > 1) {
                        that.waitTime--
                        that.codeBtnWord = `${that.waitTime}s 后重新获取`
                    } else {
                        clearInterval(timer)
                        that.codeBtnWord = '获取验证码'
                        that.getCodeBtnDisable = false
                        that.waitTime = 61
                    }
                }, 1000)
            },

            //切换登录方式
            changeLoginType() {
                if (this.loginType === 'pwd') { //切换为手机号登录
                    this.icon1 = 'el-icon-phone';
                    this.placeholder1 = 'phone';
                    this.placeholder2 = 'code';
                    this.otherLoginTitle = '账号密码登录';
                    this.loginType = 'phone';
                    this.$message.success('已切换为手机号登录');
                } else {
                    this.icon1 = 'el-icon-lx-people';
                    this.placeholder1 = 'username';
                    this.placeholder2 = 'password';
                    this.loginType = 'pwd';
                    this.otherLoginTitle = '手机号登录';
                    this.$message.success('已切换为账号密码登录');
                }

            },
            submitForm() {
                this.$refs.login.validate(valid => {
                    if (valid) {
                        const _this = this;
                        if (this.loginType === 'pwd') { //密码登录
                            //发起登录请求
                            axios.post(_this.APIurl.apiUrl.domainName + 'user/login', this.param)
                                .then(function (resp) {
                                    if (resp.data.code === 0) {
                                        _this.$message.success('登录成功');
                                        //向localStorage中存储返回信息
                                        _this.setData(resp);
                                        _this.$router.push('/');
                                    } else {
                                        _this.$message.error(resp.data.msg);
                                    }
                                })
                        } else {  //手机号登录
                            _this.phoneLoginForm.phone = _this.param.username;
                            _this.phoneLoginForm.code = _this.param.password;
                            _this.phoneLoginForm.role = _this.param.role;
                            //发起手机号码登录请求
                            _this.$http.post('dev-api/user/phoneLogin', _this.phoneLoginForm)
                                .then(function (resp) {
                                    if (resp.data.code === 0) {
                                        _this.$message.success('登录成功');
                                        //向localStorage中存储返回信息
                                        _this.setData(resp);
                                        _this.$router.push('/');
                                    } else {
                                        _this.$message.error(resp.data.msg);
                                    }
                                })
                        }
                    } else {
                        this.$message.error('请输入登录数据');
                        console.log('error submit!!');
                        return false;
                    }
                });
            },

            setData(resp) {
                localStorage.setItem("token", resp.data.data.token);
                localStorage.setItem("username", resp.data.data.username);
                localStorage.setItem("nickname", resp.data.data.nickname);
                localStorage.setItem("iconUrl", resp.data.data.iconUrl);
                localStorage.setItem("loginRole", resp.data.data.loginRole);
            },

            aaaa() {
                if (this.loginType === 'pwd') { //密码登录
                    //发起登录请求
                    axios.post(_this.APIurl.apiUrl.domainName + 'user/login', this.param)
                        .then(function (resp) {
                            if (resp.data.code === 0) {
                                _this.$message.success('登录成功');
                                //向localStorage中存储返回信息
                                _this.setData(resp);
                                _this.$router.push('/');
                            } else {
                                _this.$message.error(resp.data.msg);
                            }
                        })
                } else {  //手机号登录
                    _this.phoneLoginForm.phone = _this.param.username;
                    _this.phoneLoginForm.code = _this.param.password;
                    _this.phoneLoginForm.role = _this.param.role;
                    //发起手机号码登录请求
                    _this.$http.post('dev-api/user/phoneLogin', _this.phoneLoginForm)
                        .then(function (resp) {
                            if (resp.data.code === 0) {
                                _this.$message.success('登录成功');
                                //向localStorage中存储返回信息
                                _this.setData(resp);
                                _this.$router.push('/');
                            } else {
                                _this.$message.error(resp.data.msg);
                            }
                        })
                }
            }
        }
    };
</script>

<style scoped>
    .login-wrap {
        position: relative;
        width: 100%;
        height: 100%;
        background-image: url(../../assets/img/bg2.jpg);
        background-size: 100%;
    }

    .ms-title {
        width: 100%;
        line-height: 50px;
        text-align: center;
        font-size: 20px;
        color: #fff;
        border-bottom: 1px solid #ddd;
    }

    .ms-login {
        position: absolute;
        left: 50%;
        top: 50%;
        width: 350px;
        margin: -190px 0 0 -175px;
        border-radius: 5px;
        background: rgba(255, 255, 255, 0.3);
        overflow: hidden;
    }

    .ms-content {
        padding: 30px 30px;
    }

    .login-btn {
        text-align: center;
    }

    .login-btn button {
        width: 100%;
        height: 36px;
    }

    .phone-login {
        text-align: right;

    }

    .login-tips {
        font-size: 12px;
        line-height: 30px;
        color: #fff;
    }

    .el-button.disabled-style {
        background-color: #EEEEEE;
        color: #CCCCCC;
    }
</style>